import React, { useState, useRef } from 'react';
import { Modal, Button, message, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import type { TableListItem, TableListPagination } from '../data';
import { ModalForm, ProFormText, ProFormTextArea, ProFormRadio } from '@ant-design/pro-form';
import { codeList, addDictItem, upateDictItem, removeDictItem } from '../service';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<TableListItem>;

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  try {
    await addDictItem({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在修改');

  try {
    await upateDictItem({
      ...fields,
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

export type DictItemFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  // onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
};

const DictItemForm: React.FC<DictItemFormProps> = (props) => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '字典值',
      dataIndex: 'itemName',
    },
    {
      title: '唯一编码',
      dataIndex: 'itemValue',
    },
    {
      title: '排序',
      dataIndex: 'sort',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '启用',
        },
        0: {
          text: '禁用',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="eidt"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm key="delete" title="是否要删除此行？" onConfirm={() => handleRemove(record.id)}>
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const handleRemove = async (id: Number) => {
    const hide = message.loading('正在删除');
    try {
      await removeDictItem(id);
      hide();
      actionRef.current?.reloadAndRest?.();
      message.success('删除成功，即将刷新');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
  return (
    <Modal
      visible={props.updateModalVisible}
      width={'80%'}
      bodyStyle={{
        padding: '32px 40px 48px',
      }}
      destroyOnClose
      title="字典值管理"
      onCancel={() => {
        props.onCancel();
      }}
    >
      <ProTable<TableListItem, TableListPagination>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        headerTitle={
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新增字典项
          </Button>
        }
        // headerTitle="高级表格"
        // request={rule}
        columns={columns}
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params,
          sorter,
          filter,
        ) => {
          // console.log(params, sorter, filter);
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          let query = {
            eqQuery: {
              dictCode: props.values.dictCode,
            },
            pageNum: params.current,
            pageSize: params.pageSize,
          };
          const msg = await codeList(query);
          if (msg.code == 200) {
            return {
              data: msg.data.list,
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: msg.message,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: msg.data.total,
            };
          } else {
          }
        }}
      />
      {createModalVisible ? (
        <ModalForm
          title={currentRow ? '编辑字典项' : '新增字典项'}
          width="800px"
          layout="horizontal"
          {...formItemLayout}
          visible={createModalVisible}
          initialValues={currentRow || {}}
          onVisibleChange={handleModalVisible}
          onFinish={async (value) => {
            value.dictCode = props.values.dictCode;
            value.dictId = props.values.id;
            let success;
            if (currentRow) {
              value.id = currentRow.id;
              success = await handleUpdate(value as TableListItem);
            } else {
              success = await handleAdd(value as TableListItem);
            }
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormText
            rules={[
              {
                required: true,
                message: '请输入字典值',
              },
            ]}
            label="字典值"
            width="md"
            name="itemName"
          />
          <ProFormText
            rules={[
              {
                required: true,
                message: '请输入唯一编码',
              },
            ]}
            label="唯一编码"
            width="md"
            name="itemValue"
          />
          <ProFormRadio.Group
            options={[
              {
                value: '0',
                label: '禁用',
              },
              {
                value: '1',
                label: '启用',
              },
            ]}
            label="状态"
            name="status"
          />
          <ProFormText
            rules={[
              {
                required: false,
                message: '请输入排序',
              },
            ]}
            label="排序"
            width="md"
            name="sort"
          />
          <ProFormTextArea width="md" name="remark" label="备注" />
        </ModalForm>
      ) : null}
    </Modal>
  );
};

export default DictItemForm;
